/**
 * Create by ray at 2015年6月4日 下午4:13:48.
 * Ray [email:rayinhangzhou@126.com]
 * TrackInterceptor.java is for :
 * TODO
 * Revision History
 * Date@Programmer: memo
 * ----------------------------------------------------------------
 * 2015年6月4日@Ray: initial
 **/
package com.souche.employment.interceptor;

import com.souche.employment.cache.RedisService;
import com.souche.employment.domain.UserDO;
import com.souche.employment.dto.LoginDto;
import com.souche.employment.mapper.UserMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

public class LoginInterceptor extends HandlerInterceptorAdapter {
    @Autowired
    private RedisService redisService;
    @Autowired
    private UserMapper userMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = "";
        Cookie[] cookies = request.getCookies();
        for (int i = 0; i < cookies.length; i++) {
            Cookie cookie = cookies[i];
            if (cookie.getName().equals("TT")) {
                token = cookie.getValue();
                break;
            }
        }
        if (StringUtils.isBlank(token) || redisService.get(token) == null) {
            response.sendRedirect(request.getContextPath() + "/login");
            return false;
        } else {
            redisService.expire(token, 12 * 60 * 60);
            LoginDto loginDto = (LoginDto) redisService.get(token);
            UserDO userDO = userMapper.getUserByLoginMail(loginDto.getMail());
            Map<String, String> map = new HashMap<>();
            map.put("name", userDO.getName());
            map.put("mail", userDO.getId());
            map.put("token", token);
            map.put("type", userDO.getType());
            AuthHolder.map(map);
        }
        return true;
    }

}
